<template>
  <div class="wrap">
    <div class="header">
      <div class="search-item" v-if="$store.getters.roleType==null||$store.getters.roleType=='supervise'">
        <div class="search-box" >
          <div
            class="left"
          >
            <el-checkbox
              style="display: inline-block;margin-right: 30px"
              class="mgb10"
              v-model="checkAllUser"
             @change="handleCheckAllUser"
              :disabled="loading"
            >
              全部运营
            </el-checkbox>
            <el-checkbox
              class="mgb10"
              v-for="item in userOptions"
              :label="item.label"
              :key="item.label"
              :value="queryParams.userIds.indexOf(item.label) !== -1"
             @change="checkUser(item,$event);changeOption();changeOption2();"
              :disabled="loading"
            >
              {{item.text}}({{item.orderNum}})
            </el-checkbox>
          </div>
        </div>
            <div style="height: 1px;width: 100%;background-color: #F2F2F2"></div>
      </div>
      <div class="search-item">
        <diy-date :set-day-type="30" v-model="queryParams.time" @change="changeOption();changeOption2();"></diy-date>
      </div>

      <div class="search-item">
        <el-radio-group v-model="queryParams.tabType" size="small" @change="changeOption();changeOption2()">
          <el-radio-button class="mgb10" :label="-1">{{ $t('order.awaitSheet') }}({{attrNumber(orderNum.awaitSheetNum)}})</el-radio-button>
          <el-radio-button class="mgb10" :label="1">{{ $t('order.untreated') }}({{attrNumber(orderNum.untreatedNum)}})</el-radio-button>
          <el-radio-button class="mgb10" :label="6">{{ $t('order.waitPicked') }}({{attrNumber(orderNum.waitPickNum)}})</el-radio-button>
          <el-radio-button class="mgb10" :label="2">{{ $t('order.shipped') }}({{attrNumber(orderNum.sendNum)}})</el-radio-button>
          <el-radio-button class="mgb10" :label="4">{{ $t('order.canceled') }}({{attrNumber(orderNum.cancelNum)}})</el-radio-button>
          <el-radio-button class="mgb10" :label="0">{{ $t('order.allOrders') }}({{attrNumber(orderNum.totalNum)}})</el-radio-button>
        </el-radio-group>
      </div>
      <div class="search-item">
        <div class="search-box">
          <div class="left">
            <el-select
                v-model="queryParams.goodsType"
                size="small"
                @change="changeOption"
                class="mgr10 mgb10"
                style="width: 150px"
                clearable
            >
              <el-option :label="$t('order.allListing')" value=""></el-option>
              <el-option :label="$t('order.multipleListing')" :value="1"></el-option>
              <el-option :label="$t('order.singleListing')" :value="2"></el-option>
            </el-select>

            <el-select
                v-model="queryParams.skuType"
                size="small"
                @change="changeOption"
                class="mgr10 mgb10"
                style="width: 150px"
                clearable
            >
              <el-option :label="$t('order.allVariants')" value=""></el-option>
              <el-option :label="$t('order.multipleSKU')" :value="1"></el-option>
              <el-option :label="$t('order.singleSKU')" :value="2"></el-option>
            </el-select>
            <el-select
                v-model="queryParams.serveType"
                size="small"
                class="mgr10 mgb10"
                @change="changeOption"
                style="width: 150px"
                clearable>
              <el-option :label="$t('order.allPackagingServices')" value=""></el-option>
              <el-option :label="$t('order.packaged')" :value="1"></el-option>
              <el-option :label="$t('order.unpackaged')" :value="2"></el-option>
            </el-select>
            <el-select
              v-model="queryParams.shippingType"
              size="small"
              class="mgr10 mgb10"
              @change="changeOption"
              style="width: 150px"
              clearable>
              <el-option label="面单类型" value=""></el-option>
              <el-option label="平台面单" :value="1"></el-option>
              <el-option label="物流面单" :value="0"></el-option>
            </el-select>
          </div>

          <div class="right">
            <div style="display: inline-block;margin-right: 20px;width: 540px">
              <el-input
                  size="small"
                  style="width: 280px; margin-right: 10px; margin-bottom: 10px"
                  v-model="queryParams.keyword"
                  :placeholder="$t('order.searchForOrderID/Listing ID/SKU')"
                  @keyup.enter.native="changeOption(true)"
                  clearable @clear="changeOption(false, 'clear')"></el-input>
              <el-button size="small" type="primary" @click="changeOption(true)">{{ $t('common.search') }}</el-button>
              <export-button :func="getPacketOrderList" :query-params="queryParams" :exportType="'user_packet_order_list'" :getTotal="total"></export-button>
              <!--<export-button :func="getPacketOrderList" :query-params="queryParams"></export-button>-->
            </div>
          </div>
        </div>
      </div>


    </div>
    <div class="content">

      <el-table
          v-loading="loading"
          :data="data"
          border
          v-tableHeight="{bottomOffset: 80}"
          height="100px"
          ref="tableData"
      >
        <el-table-column
            prop="orderId"
            :label="$t('table.orderId')"
            align="center"
            min-width="150"
            fixed
        >
        </el-table-column>
        <el-table-column
            prop="goodsImage"
            :label="$t('table.productCover')"
            align="center"
            width="120"
        >
          <template slot-scope="{row}">
            <template v-if="row.subOrders.length === 1">
              <div class="img-box img-one">
                <img :src="row.subOrders[0].goodsImage" alt=""/>
              </div>
            </template>
            <template v-else>
              <div class="img-box">

                <img
                    v-for="(subOrder) in row.subOrders.slice(0,4)"
                    :key="subOrder.subOrderId"
                    :src="subOrder.goodsImage"
                    alt=""
                />
              </div>
            </template>
          </template>

        </el-table-column>
        <el-table-column
            prop="listing"
            label="Listing ID与SKU"
            align="center"
            min-width="300"
        >
          <template slot-scope="{row}">
            <div
                v-for="subOrder in row.subOrders"
                :key="subOrder.subOrderId"
            >
              <template v-if="subOrder.is_packet">
                {{subOrder.sku}}
              </template>
              <template v-else>
                {{subOrder.goodsId}}({{subOrder.sku}})
              </template>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="num"
            :label="$t('table.productQuantity')"
            align="center"
            width="100"
        >
        </el-table-column>
        <el-table-column
            prop="spStickerPrice"
            :label="$t('packet.贴单单价（元）')"
            align="center"
            width="140"
        >
          <template slot-scope="{row}">
            <template v-if="row.orderStatus === 1">
              {{row.packetOrder.preSpStickerPrice}}
            </template>
            <template v-else>
              {{row.packetOrder.spStickerPriceV2}}
            </template>
            <!--<div :class="row.refundSticker ? 'refund' : ''">-->
            <!--  {{row.packetOrder.spStickerPrice}}-->
            <!--</div>-->
          </template>
        </el-table-column>
        <el-table-column
            prop="totalStickerAppend"
            :label="$t('packet.续件单价（元）')"
            align="center"
            width="140"
        >
          <template slot-scope="{row}">
            <template v-if="row.orderStatus === 1">
              {{row.packetOrder.preStickerAppend}}
            </template>
            <template v-else>
              {{row.packetOrder.stickerAppendV2}}
            </template>
            <!--<div :class="row.refundSticker ? 'refund' : ''">-->
            <!--  {{row.packetOrder.totalStickerAppend}}-->
            <!--</div>-->
          </template>
        </el-table-column>
        <el-table-column
            prop="packageMaterialPrice"
            :label="$t('packet.包装服务费（元）')"
            align="center"
            width="140"
        >
          <template slot-scope="{row}">
            <template v-if="row.orderStatus === 1">
              {{row.packetOrder.prePackingCharge}}
            </template>
            <template v-else>
              {{row.packetOrder.packingChargeV2}}
            </template>
            <!--<div :class="row.refundSticker ? 'refund' : ''">-->
            <!--  {{row.packetOrder.packageMaterialPrice}}-->
            <!--</div>-->
          </template>
        </el-table-column>
        <!--<el-table-column-->
        <!--    prop="userShippingFee"-->
        <!--    :label="$t('packet.运费（元）')"-->
        <!--    align="center"-->
        <!--    width="140"-->
        <!--&gt;-->
        <!--  <template slot-scope="{row}">-->
        <!--    <div :class="row.refundShippingFee ? 'refund' : ''">-->
        <!--      {{row.packetOrder.userShippingFee}}-->
        <!--    </div>-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <el-table-column
          :label="$t('packet.快递加收（元）')"
          align="center"
          width="140"
        >
          <template slot-scope="{row}">
            <template v-if="row.orderStatus === 1">
              {{row.packetOrder.preLogisticTypePrice}}
            </template>
            <template v-else>
              {{row.packetOrder.logisticTypePriceV2}}
            </template>
            <!--<div :class="row.refundShippingFee ? 'refund' : ''">-->
            <!--  {{row.packetOrder.userShippingFee}}-->
            <!--</div>-->
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('packet.总贴单费用（元）')"
          align="center"
          width="140"
        >
          <template slot-scope="{row}">
            {{row.packetOrder.allAmount}}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('packet.物流信息')"
          align="center"
          width="200"
        >
          <template slot-scope="{row}">
            <template v-if="row.shippingType === 0">
              <template v-if="row.logisticsArr.length > 0">
                <div
                  v-for="(logistics, index) in row.logisticsArr"
                  :key="index"
                >
                  <template v-if="logistics.logistics_type === 'FedEx' || logistics.logistics_type === 'iMile'">
                    <el-button type="text" style="color: #606266;" @click="toggleDetails(logistics)">{{logistics.tracking_number_info}}</el-button>
                    <i class="el-icon-search mgl10" style="cursor: pointer; color: #1890ff;" @click="toggleDetails(logistics)"></i>
                  </template>
                  <template v-else>
                    {{logistics.tracking_number_info}}
                  </template>
                </div>
              </template>
              <template v-else>
                {{row.packetOrder.logisticsType}} - {{row.packetOrder.trackingNumber}}
              </template>
            </template>
            <template v-else>
              平台面单
            </template>
          </template>
        </el-table-column>
        <el-table-column
            prop="statusStr"
            :label="$t('table.status')"
            align="center"
            width="100"
        >
        </el-table-column>
        <el-table-column
            prop="createTime"
            :label="$t('packet.制单时间')"
            align="center"
            min-width="200"
        >
          <template slot-scope="{row}">
            {{row.packetOrder.createTime || '-'}}
          </template>
        </el-table-column>
        <el-table-column
            prop="stickerTime"
            :label="$t('packet.发货时间')"
            align="center"
            min-width="200"
        >
          <template slot-scope="{row}">
            {{row.packetOrder.stickerTime || '-'}}
          </template>
        </el-table-column>
        <el-table-column
            prop="cancelDate"
            :label="$t('packet.取消时间')"
            align="center"
            min-width="200"
        >
          <template slot-scope="{row}">
            {{row.packetOrder.cancelDate || '-'}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作员"
          prop="userAccount"
          align="center"
          min-width="150"
        >
          <template v-slot="{row}">
            <template v-if="row.child_name">
               {{row.child_name}}
            </template>
            <template v-else>
               {{row.userAccount}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('packet.操作')"
          min-width="200"
          fixed="right"
        >
          <template slot-scope="{row}">
            <el-button size="mini" type="primary" @click="toDetail(row)" v-if="row.orderStatus !== 1">{{ $t('packet.查看') }}</el-button>
            <el-button size="mini" type="primary" @click="toUpdateOrder(row)" v-if="row.orderStatus === 1">{{ $t('packet.修改订单') }}</el-button>
            <el-button size="mini" type="danger" @click="cancelOrder(row)" v-if="row.orderStatus === 1">{{ $t('packet.取消订单') }}</el-button>
          </template>
        </el-table-column>

      </el-table>


      <div class="page-wrap">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page.sync="queryParams.page"
            :page-size="queryParams.pageSize"
            :total="total"
            @current-change="getData"
            :page-sizes="[10, 20, 50, 100, 500, 1000]"
            @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :title="(showTraceTrackingNumberInfo === null) ? `物流轨迹 ` : `物流轨迹 ` + showTraceTrackingNumberInfo"
      :visible.sync="showTraceDialog"
      width="500px"
    >
      <template v-if="showTraceData !== null">
        <div
          v-for="(traceItem, traceIndex) in showTraceData"
          :key="traceIndex"
          :style="{ color: traceIndex === 0 ? 'initial' : '#AAAAAA' }"
        >
          <template v-if="showTraceLogisticsType === 'FedEx'">
            <span>{{ traceItem.date }}</span>
            <br>
            <span v-if="traceItem.scanLocation['city'] !== null && traceItem.scanLocation['city'] !== false && traceItem.scanLocation['city'] !== undefined">【{{ traceItem.scanLocation['city'] }}】</span> <span>{{ traceItem.eventDescription }}</span>
            <br>
            <br>
          </template>
          <template v-else>
            <span>{{ traceItem.latestStatusTime }}</span>
            <br>
            <span>{{ traceItem.locusDetailed }}</span>
            <br>
            <br>
          </template>
        </div>
      </template>
      <template v-else>
        <div v-loading="showTraceLoading"></div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import {attrNumber} from "@/utils/common";
import {
  getLogisticOrderTrace

} from "@/api/order";
import {deepCopy} from "@/utils";
import DiyDate from "@/views/order/components/DiyDate.vue";
import ExportButton from "@/views/order/components/ExportButton.vue";
import {cancelPacketOrder, getPacketOrderList, getPacketOrderListNum,getChildUserList} from "@/api/packetOrders";

export default {
  name: "orderList",
  components: {
    ExportButton,
    DiyDate,
  },
  data(){
    return {
      loading: false,
      orderGoodsItemLoading: false,
      queryParams: {
        page: 1,
        pageSize: 10,
        tabType : 1, // 状态
        goodsType : '', //  商品类型
        skuType: '', // 库存类型
        keyword: '',
        time: [],
        serveType: '',
        shippingType: '',
        userIds:[],
      },
      data:[],
      total: 0,
      // 订单数量
      orderNum:{
        cancelNum: 0,
        finishNum: 0,
        ignoreNum: 0,
        returnNum: 0,
        sendNum: 0,
        totalNum:0,
        awaitSheetNum:0,
        untreatedNum:0,
        waitPickNum: 0,
        pickedNum: 0,
      },
      checkAllFlag: false,
      orderGoodsItem:[], //
      attrNumber,
      is_search: false,
      getPacketOrderList,
      showTraceDialog: false,
      showTraceLoading: false,
      showTraceAbbreviateData: null,
      showTraceData: null,
      showTraceInfo: false,
      showTraceLogisticsType: null,
      showTraceTrackingNumberInfo: null,
       userOptions:[],
        checkAllUser:true,
    }
  },
  created() {
    // this.setQueryParams()
    this.getAllData()


  },
  updated () {
    this.$nextTick(() => {
      this.$refs['tableData'].doLayout();
    })
  },
  computed:{
    tableData(){
      const tableDate = [];
      this.data.forEach(item=>{
        const obj = item;
        tableDate.push(obj)
      })
      return tableDate;
    },
  },
  mounted() {
    window.addEventListener('resize', this.onWindowResize);

  },
  methods:{
    // 选择运营
    checkUser(account,$event){
      if(this.checkAllUser === true){
        this.queryParams.userIds = [account.label];
        this.checkAllUser = false
      }else{
        const index = this.queryParams.userIds.indexOf(account.label)
        if(index === -1){
          this.queryParams.userIds.push(account.label)
        }else{
          this.queryParams.userIds.splice(index,1)
        }
      }

    },
    handleCheckAllUser(){
      this.queryParams.userIds = []
      if(this.checkAllUser){
        this.userOptions.forEach(item=>{
          this.queryParams.userIds.push(item.label)
        })
      }
      this.changeOption();
      this.changeOption2();
    },
    onWindowResize() {
      if (this.$refs.accountIdsCheckBox) {
        this.$refs.accountIdsCheckBox.dispatchEvent(new Event('resize'));
      }
    },
     getAllData(){
      // 获取所有店铺
      this.queryParams.page = 1;
      this.checkAllUser = true;
       this.getChildList()

    },
    getChildList(){
      getChildUserList()
          .then(res=>{
               res.data.forEach(item=>{
                 const obj = {
                   label: item.id,
                   text: item.name,
                   orderNum: item.order_num,
                 }
                 this.userOptions.push(obj);
                 this.queryParams.userIds.push(obj.label)
               })
               this.getData()
               this.getOrderListNum()
               console.log(  this.queryParams.userIds);
          })

    },
    // 获取表单数据
    getData(){
      this.loading = true
      getPacketOrderList(this.queryParams)
          .then(res=>{
            const info = res.info
            this.data = res.data
            this.total = res.info.total
            this.loading = false;
          })
    },
    // 触发变更事件
    changeOption(is_search = false, type = ''){
      if (is_search == true) {
        //判断是否使用过搜索按钮
        this.is_search = true
      }
      if (type == 'clear') {
        if (this.is_search == false) {
          return
        } else {
          this.is_search = false
        }
      }
      this.checkAllUser = this.userOptions.length === this.queryParams.userIds.length;
      this.queryParams.page = 1
      this.getData()
    },
    handleSizeChange(val){
      this.queryParams.pageSize = val;
      this.queryParams.page = 1
      this.getData();
    },
    // 触发某些事件改变数据（改变聚合搜索模块 改变店铺数量）
    changeOption2(){
      this.getOrderListNum()
    },
    onContainerResize(){
      return;
    },
    // 获取订单的数量
    getOrderListNum(){
      getPacketOrderListNum(this.queryParams)
          .then(res =>{
            this.orderNum.cancelNum = res.data.cancelNum;
            this.orderNum.finishNum = res.data.finishNum;
            this.orderNum.ignoreNum = res.data.ignoreNum;
            this.orderNum.returnNum = res.data.returnNum;
            this.orderNum.sendNum = res.data.sendNum;
            this.orderNum.totalNum = res.data.totalNum;
            this.orderNum.awaitSheetNum = res.data.awaitSheetNum;
            this.orderNum.untreatedNum = res.data.untreatedNum;
            this.orderNum.waitPickNum = res.data.waitPickNum;
            this.orderNum.pickedNum = res.data.pickedNum;

          })
    },
    toDetail(row) {
      this.$router.push({
        path: '/packetOrders/packetOrderInfo',
        query: {
          orderId: row.orderId
        }
      })
    },
    toUpdateOrder(row) {
      this.$router.push({
        path: '/packetOrders/updatePacketOrder',
        query: {
          orderId: row.orderId
        }
      })
    },
    cancelOrder(row) {
      this.$warningBox(this.$t('packet.取消后当前订单将从系统删除'), this.$t('packet.取消当前订单？'))
          .then(() => {
            this.loading = true;
            cancelPacketOrder(row.orderId)
                .then(res => {
                  this.loading = false;
                  this.$successMessage(this.$t('packet.取消订单成功'));
                  this.getData();
                });
          })
    },

    toggleDetails(traceData){
      this.showTraceDialog = true
      this.showTraceLoading = true

      this.showTraceAbbreviateData = null
      this.showTraceData = null
      this.showTraceInfo = false
      this.showTraceLogisticsType = null
      this.showTraceTrackingNumberInfo = null

      const postData = {
        'orderId': traceData.orderId,
        'accountType': traceData.accountType,
        'trackingNumber': traceData.tracking_number,
      }

      // 发起查询
      getLogisticOrderTrace(postData)
        .then(res=>{
          this.showTraceLoading = false
          if(res.error === 0){
            this.showTraceAbbreviateData = res.data.traceAbbreviate
            this.showTraceData = res.data.trace
            this.showTraceInfo = false
            this.showTraceLogisticsType = res.data.logistics_type
            this.showTraceTrackingNumberInfo = res.data.tracking_number_info
          }else{
            if (traceData.trace !== null) {
              this.showTraceAbbreviateData = traceData.traceAbbreviate
              this.showTraceData = traceData.trace
              this.showTraceInfo = false
              this.showTraceLogisticsType = traceData.logistics_type
              this.showTraceTrackingNumberInfo = traceData.tracking_number_info
            }
          }
        })
    },

    toggleItemDetails(){
      this.showTraceInfo = !this.showTraceInfo
    },

  },

}
</script>

<style scoped lang="less">
.wrap {
  padding: 30px 30px;
  .header{
    .search-item{
      margin-bottom: 20px;
      .search-box{
        display: flex;
        justify-content: space-between;
        .hidden-account-options {
          overflow: hidden;
          max-height: 29px;
          max-height: 29px;
        }
        .left{

        }
      }
    }
  }
  .page-wrap{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 0px 0 0;
  }
  .table-order{
    p{
      margin: 0;
      padding: 0;
    }
    font-size: 13px;
  }
}
.order-item{
  min-height: 200px;
  width: 100%;
}
.page-wrap{
  margin-top: 20px;
}
</style>

<style lang="less">
.header{
  .el-radio-button__inner{
    padding: 8px 20px;
  }
}
.channel-form{
  &.el-form{
    .el-form-item__label{
      word-break: break-word;
    }
  }
}
.channel-box-card{
  .el-card__header{
    padding: 5px 10px;
    font-size: 12px;
    line-height: 26px;
  }
  .el-card__body{
    padding: 0;
  }
}
.query-select{
  margin-right: 20px;
}

</style>
